# coding=utf-8
# author:xc
# datetime:2018/8/1 9:19

from flask import render_template, request, make_response, jsonify, redirect
import time
from . import admin
from app.MySession import MySession
from dbConnection.MysqlConn import Mysql
from app import util


@admin.route('/admin/login.html', methods=['POST', 'GET'])
def admin_login():
    if request.method == "GET":
        return render_template('/admin/login.html')
    else:
        try:
            username = request.values.get("username")
            password = request.values.get("password")
            ip = request.headers.get('X-Real-Ip', request.remote_addr)
            password = util.md5(str(password))
            sql = "select * from user_admin where username='%s' and status=1" % username
            mysql = Mysql()
            res = mysql.getOne(sql, None)
            if res:
                l = res
                # if l['login_error'] >= 5:
                #     status = 'permission deny ! ! !'
                #     r_sql = 'insert into login_record values (%s,"%s","%s","%s","5s")' \
                #             % ('null', username, ip, u'账号被锁定', int(time.time()))
                #     mysql.insertOne(r_sql, None)
                # else:
                if l['password'] == password:
                    r_sql = 'insert into login_record VALUES (%s,"%s","%s","%s",%s)' \
                            % ('null', username, ip, u'登陆成功', int(time.time()))
                    mysql.insertOne(r_sql, None)
                    count = int(l['login_count']) + 1
                    sql = 'update user_admin set login_error = 0,login_count = "%s",login_ip = "%s",login_time = now()' \
                          % (count, ip)
                    mysql.update(sql, None)
                    status = 'success'
                    data = {
                        'status': status
                    }
                    re = make_response(jsonify(data))
                    user = MySession.create_session(username)
                    re.set_cookie('uid', user)
                    mysql.dispose()
                    return re
                else:
                    r_sql = 'insert into login_record VALUES (%s,"%s","%s","%s",%s)' \
                            % ('null', username, ip, '密码错误', int(time.time()))
                    mysql.insertOne(r_sql, None)
                    count = int(l['login_error']) + 1
                    sql = 'update user_admin set login_error = "%s",login_ip = "%s",login_time = now() where username="%s"' \
                          % (count, ip, username)
                    mysql.update(sql, None)
                    status = 'error'
            else:
                r_sql = 'insert into login_record(uname,login_ip,login_status,login_time) VALUES ("%s","%s","%s",%s)' \
                        % (username, ip, '账号不存在', int(time.time()))
                mysql.insertOne(r_sql, None)
                status = 'error'
            mysql.dispose()
        except Exception as e:
            print e
            status = 'error'
        data = {
            'status': status
        }
        return jsonify(data)


@admin.route('/admin/logout')
@util.admin_login
def logout():
    resp = make_response(redirect('/admin/login.html'))
    resp.delete_cookie('uid')
    users = request.cookies.get(request.cookies.get('uid'))
    if users:
        resp.delete_cookie(users)
    return resp


# 修改管理员密码
@admin.route('/admin/update/password', methods=['POST', 'GET'])
@util.admin_login
def admin_update_password():
    session = request.cookies.get("uid")
    username = MySession.get_name(session)
    old_password = request.values.get('old_password')
    password = request.values.get('password')
    mysql = Mysql()
    old_password = util.md5(str(old_password))
    sql2 = 'select * from user_admin where username = "%s" and password = "%s"' % (username, old_password)
    result = mysql.getOne(sql2, None)
    if result is not None:
        password = util.md5(str(password))
        sql = 'update user_admin set password = "%s" where username = "%s"' % (password, username)
        data = mysql.update(sql, None)
        if data > 0:
            data1 = {
                'res': 'success'
            }
            resp = make_response();
            resp.delete_cookie('uid')
    else:
        data1 = {
            'res': 'error'
        }
    mysql.dispose()
    return jsonify(data1)
